#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include "FTHeader.h"

FTHeader *createFTHeader(ssize_t num) {
	FTHeader *header = (FTHeader *) malloc(sizeof(FTHeader));
	if (header == NULL) {
		fprintf(stderr, "malloc FTHeader failed!\n");
		return NULL;
	}
	header->data = (char *) malloc(sizeof(char ) * num);
	if (header->data == NULL) {
		fprintf(stderr, "malloc FTHeader data failed!\n");
		free(header);
		return NULL;
	}
	memset(header->data, 0, sizeof(char ) * num);
	header->pos = 0;
	header->capacity = num;
	return header;
}

void releaseFTHeader(FTHeader *header) {
	if (header) {
		if (header->data) {
			free(header->data);
		}
		free(header);
	}
}

int initFTHeader(FTHeader *header, int sock_fd, const char *flags) {
	ssize_t ret;

	while (strstr(header->data, flags) == NULL) {
		ret = recv(sock_fd, header->data + header->pos, header->capacity - header->pos, 0);
		if (ret < 0) {
			perror("rcv loop");
			return -1;
		}
		header->pos += ret;
		if (ret == 0) {
			printf("remote closed!\n");
			return -1;
		}
	}
	return 0;
}


